import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '../store'
import { errors } from '../api/error'
import { getClientInfo } from './client_info'
import { getBaseUrl } from './baseUrl'
import { getReqModel } from './sign'

const service = axios.create({
  baseURL: window.location.host.indexOf('localhost') === -1 ? window.appConfig.aloha : getBaseUrl(),
  timeout: 120000
})

service.defaults.headers.post['Content-Type'] = 'application/json'

service.interceptors.request.use(
  (config) => {
    if (store.getters.token) {
      config.headers['Authorization'] = JSON.stringify({ token: store.getters.token })
      config.headers['clientInfo'] = getClientInfo()
      config.headers['userToken'] = store.getters.token
      config.headers['appName'] = window.appConfig.source
    }
    let req_model = {
      appName: '',
      format: '',
      sign: '',
      source: '',
      timestamp: new Date().getTime() + '',
      version: ''
    }
    switch (config.method) {
      case 'post':
        req_model = getReqModel(config.data)
        config.data = req_model
        break
      case 'get':
        break
      case 'postout':
        config.method = 'post'
        req_model = getReqModel(config.data)
        config.data = req_model
        break
    }
    return config
  },
  (error) => {
    Message({
      message: '请求异常 ' + error.message,
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    const res = response.data
    if (!res.code && response.status === 200) {
      return res
    }
    if (res.code && res.code === 200) {
      return res
    }
    if (res.code === '-1') {
      Message({
        message: '系统错误!',
        type: 'error',
        duration: 3 * 1000
      })
      return Promise.reject('error')
    }
    if (res.code === '-500') {
      Message({
        message: res.result,
        dangerouslyUseHTMLString: true,
        type: 'error',
        duration: 3 * 1000
      })
      return Promise.reject('error')
    }
    if (res.code === '-300') {
      Message({
        message: res.result,
        type: 'error',
        duration: 2 * 1000
      })
      store.dispatch('FedLogOut').then(() => {
        setTimeout(() => {
          location.reload()
        }, 2 * 1000)
      })
      return Promise.reject('error')
    }
    if (response.config.responseType === 'blob') {
      if (response.config.filetype === 'pdf') {
        return response.data
      } else {
        return response
      }
    }
    if (res.code === 200 || res.errorCode === 0 || res.rtn === 0) {
      return res
    }
    if (response.config.responseType === 'pdf') {
      return res
    }
    // ---待定安页面定案失败错误码-450
    if (res.code === -450) {
      Message({
        message: res.result,
        type: 'error',
        duration: 3 * 1000
      })
      return
    }
    if (res.code !== '0') {
      if (res.code === '805') {
        // 如果没有之前登录就去再登录，否则弹框提示回到登录页
        if (store.getters.token) {
          MessageBox.confirm('该用户已经在其他设备登录了。请重新登录', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          }).then(() => {
            // 顶号
            store.dispatch('FedLogOut').then(() => {
              location.reload()
            })
          })
        } else {
          return Promise.resolve({ again: true })
        }
      }
      if (res.code !== '-112') {
        Message({
          message: exception(res.code, res.message),
          type: 'error',
          duration: 3 * 1000
        })
      }
      // 以下错误码处理需要强制退出登录状态的.
      // ---------------------------------------------
      if (res.code === '-2' || res.code === '804') {
        store.dispatch('FedLogOut').then(() => {
          location.reload()
        })
      }
      // ----------------------------------------------
      return Promise.reject({ e: 'error' })
    } else {
      return response.data
    }
  },
  (error) => {
    let code = ''
    if (error.response) {
      code = error.response.status
    } else {
      code = '网络已断开'
    }
    Message({
      message: '网络开小差(' + code + ')',
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject(error)
  }
)

function exception(code, message) {
  const list = errors.filter((e) => {
    return e.code === code
  })
  if (list.length === 0) {
    return message
  } else {
    return list[0].message
  }
}

const ajax = (obj) => {
  return new Promise((resolve, reject) => {
    service(obj)
      .then(res => {
        resolve(res)
      })
      .catch((e) => {
        console.log(e)
        reject()
      })
  })
}
export default ajax
